import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:myapp/api/Http.dart';
import 'package:myapp/api/Urls.dart';
import 'package:myapp/model/TopGoodsModel.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'PageOneItem.dart';

/*
 * 第一頁
 */
class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> with AutomaticKeepAliveClientMixin{

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    page = 0;
    lastId = "";
    getPageOneData();
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    page++;
    getPageOneData();
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return IndexedStack(
      children: <Widget>[
        Container(
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            header: MaterialClassicHeader(),
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                Widget body;
                if (mode == LoadStatus.idle) {
                  body = Text("上拉加载");
                } else if (mode == LoadStatus.loading) {
                  body = CupertinoActivityIndicator();
                } else if (mode == LoadStatus.failed) {
                  body = Text("加载失败！点击重试！");
                } else if (mode == LoadStatus.canLoading) {
                  body = Text("松手,加载更多!");
                } else {
                  body = Text("没有更多数据了!");
                }
                return Container(
                  height: 55.0,
                  child: Center(child: body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              itemBuilder: (c, i) =>
                  Card(child: Center(child: PageOneItem(listBean[i])),
                  margin: const EdgeInsets.all(6),),
              itemExtent: 100.0,
              itemCount: listBean.length,
            ),
          ),
        )
      ],
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPageOneData();
  }

  String lastId = '';
  List<ListBean> listBean = List();
  int page = 0;

  void getPageOneData() {
    Map<String, dynamic> paraMap = Map();
    paraMap["offset"] = page * 20;
    print(lastId);
    if (lastId.isNotEmpty) {
      paraMap["list_id"] = lastId;
    }
    paraMap["limit"] = 20;
    paraMap["sort_type"] = 2;
    DioUtils.postHttp(Urls.TopGoodsListUrl, parameters: paraMap,
        onSuccess: (data) {
      TopGoodsModel topGoodsModel = TopGoodsModel.fromMap(jsonDecode(data));
      lastId = topGoodsModel.topGoodsListGetResponse.listId;
      setState(() {
        listBean.addAll(topGoodsModel.topGoodsListGetResponse.list);
      });
      print(topGoodsModel);
    }, onError: (err) {
      print(err);
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
